<template>
  <div class="withdrawal-records">
    <div class="page-header">
      <h3>提现记录</h3>
      <div class="header-actions">
        <el-button type="primary" size="small" @click="exportData">
          <i class="el-icon-download"></i> 导出为CSV
        </el-button>
      </div>
    </div>

    <!-- 筛选表单 -->
    <el-form :inline="true" :model="filterForm" class="filter-form" size="small">
      <el-form-item label="提现时间">
        <el-date-picker
          v-model="filterForm.dateRange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 280px;"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="玩家ID">
        <el-input v-model="filterForm.uid" placeholder="请输入玩家ID" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="渠道">
        <el-select v-model="filterForm.channel" placeholder="请选择渠道" style="width: 150px;" clearable>
          <el-option
            v-for="item in channelOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="支付渠道">
        <el-input v-model="filterForm.pay_channel" placeholder="请输入支付渠道" clearable></el-input>
      </el-form-item>
      <el-form-item label="三方订单编号">
        <el-input v-model="filterForm.third_order_id" placeholder="请输入三方订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="订单编号">
        <el-input v-model="filterForm.order_id" placeholder="请输入订单编号" clearable></el-input>
      </el-form-item>
      <el-form-item label="提现金额">
        <el-input v-model="filterForm.money" placeholder="请输入提现金额" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="提现金币">
        <el-input v-model="filterForm.coin" placeholder="请输入提现金币" clearable type="number"></el-input>
      </el-form-item>
      <el-form-item label="状态">
        <el-select v-model="filterForm.status" placeholder="请选择状态" clearable style="width: 160px;">
          <el-option label="待审核" :value="1"></el-option>
          <el-option label="提现成功" :value="2"></el-option>
          <el-option label="已拒绝" :value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleFilter">搜索</el-button>
        <el-button @click="resetFilter">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table
      :data="withdrawalRecords"
      border
      style="width: 100%"
      :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      v-loading="loading"
    >
      <el-table-column prop="date" label="提现时间" width="150"></el-table-column>
      <el-table-column prop="uuid" label="uuid" width="150"></el-table-column>
      <el-table-column prop="paymentUuid" label="支付UUID" width="200"></el-table-column>
      <el-table-column prop="userChannel" label="用户渠道" width="120"></el-table-column>
      <el-table-column prop="orderId" label="订单号" width="200"></el-table-column>
      <el-table-column prop="withdrawalChannel" label="提现渠道" width="120"></el-table-column>
      <el-table-column prop="withdrawalAmount" label="提现金额" width="120"></el-table-column>
      <el-table-column prop="withdrawalCoins" label="提现金币" width="120"></el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-tag :type="getTagType(scope.row.status)">
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <div v-if="scope.row.status === '待审核'">
            <el-button
              type="success"
              size="mini"
              @click="handleApprove(scope.row)"
            >
              允许
            </el-button>
            <el-button
              type="danger"
              size="mini"
              @click="handleReject(scope.row)"
              style="margin-left: 5px;"
            >
              拒绝
            </el-button>
          </div>
          <span v-else style="color: #909399;">无操作</span>
        </template>
      </el-table-column>
      <el-table-column prop="noRefund" label="拒绝的话不退回金币" width="150" class-name="red-column"></el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { cashoutRecord, channelOpen, recordAgree } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'
import channelMixin from '@/mixins/channelMixin'

export default {
  name: 'WithdrawalRecords',
  mixins: [channelMixin],
  data() {
    return {
      filterForm: {
        dateRange: [],
        uid: '',
        channel: null,
        pay_channel: '',
        third_order_id: '',
        order_id: '',
        money: '',
        coin: '',
        status: ''
      },
      withdrawalRecords: [],
      originalRecords: [], // 用于存储原始数据
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      exportLoading: false
    }
  },
  methods: {
    getTagType(status) {
      switch (status) {
        case '提现成功':
          return 'success'
        case '已拒绝':
          return 'danger'
        case '待审核':
          return 'warning'
        default:
          return 'info'
      }
    },
    getStatusText(status) {
      switch (status) {
        case 1:
          return '待审核'
        case 2:
          return '提现成功'
        case 3:
          return '已拒绝'
        default:
          return '未知'
      }
    },
    getStatusNumber(statusText) {
      switch (statusText) {
        case '待审核':
          return 1
        case '提现成功':
          return 2
        case '已拒绝':
          return 3
        default:
          return 0 // 0表示任意
      }
    },
    handleApprove(row) {
      this.$confirm('确认允许此提现申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const params = {
            id: row.id, // 使用提现记录ID
            agree: 1 // 1表示同意
          }
          
          console.log('允许提现参数:', params)
          
          const response = await recordAgree(params)
          
          if (response && response.code === 0) {
            row.status = '提现成功'
            this.$message.success('提现已允许')
            // 刷新列表数据
            this.fetchData()
          } else {
            this.$message.error(response.msg || response.message || '审核失败')
          }
        } catch (error) {
          console.error('允许提现失败:', error)
          this.$message.error('操作失败: ' + error.message)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    },
    handleReject(row) {
      this.$confirm('确认拒绝此提现申请？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.loading = true
        try {
          const params = {
            id: row.id, // 使用提现记录ID
            agree: 0 // 0表示拒绝
          }
          
          console.log('拒绝提现参数:', params)
          
          const response = await recordAgree(params)
          
          if (response && response.code === 0) {
            row.status = '已拒绝'
            this.$message.success('提现已拒绝')
            // 刷新列表数据
            this.fetchData()
          } else {
            this.$message.error(response.msg || response.message || '审核失败')
          }
        } catch (error) {
          console.error('拒绝提现失败:', error)
          this.$message.error('操作失败: ' + error.message)
        } finally {
          this.loading = false
        }
      }).catch(() => {
        // 用户取消操作
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.fetchData()
    },
    async fetchData() {
      this.loading = true
      try {
        const params = {
          uid: this.filterForm.uid ? parseInt(this.filterForm.uid) : 0, // 玩家ID
          channel: this.formatChannelParam(this.filterForm.channel), // 渠道
          pay_channel: this.filterForm.pay_channel || '', // 支付渠道
          third_order_id: this.filterForm.third_order_id || '', // 三方订单编号
          order_id: this.filterForm.order_id || '', // 订单编号
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? 
            this.filterForm.dateRange[0] : '', // 提现起始时间
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? 
            this.filterForm.dateRange[1] : '', // 提现结束时间
          money: this.filterForm.money ? parseInt(this.filterForm.money) : 0, // 提现金额
          coin: this.filterForm.coin ? parseInt(this.filterForm.coin) : 0, // 提现金币
          status: this.filterForm.status || 0, // 1:待审核 2:提现成功 3:已拒绝
          page: this.currentPage,
          page_size: this.pageSize
        }
        
        console.log('===== WithdrawalRecords Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await cashoutRecord(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          console.log('接口成功，response.data:', response.data)
          console.log('response.data的类型:', typeof response.data)
          console.log('response.data的结构:', Object.keys(response.data || {}))
          
          // 尝试多种可能的数据结构
          let records = []
          if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
            console.log('使用 response.data.records')
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
            console.log('使用 response.data.list')
          } else if (Array.isArray(response.data)) {
            records = response.data
            console.log('使用 response.data 直接数组')
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
            console.log('使用 response.data.data')
          } else {
            console.log('未找到数组数据，尝试遍历所有属性:')
            if (response.data && typeof response.data === 'object') {
              for (let key in response.data) {
                console.log(`response.data.${key}:`, response.data[key], 'isArray:', Array.isArray(response.data[key]))
                if (Array.isArray(response.data[key])) {
                  records = response.data[key]
                  console.log(`找到数组数据在 response.data.${key}`)
                  break
                }
              }
            }
          }
          
          console.log('解析后的records:', records)
          console.log('records长度:', records.length)
          console.log('records第一条数据:', records[0])
          
          // 映射数据字段
          this.withdrawalRecords = records.map(record => ({
            id: record.id || record.uid, // 提现记录ID，如果没有id字段则使用uid
            date: record.create_time || record.update_time || '',
            uuid: record.uid || '',
            paymentUuid: record.third_order_id || '',
            userChannel: record.channel || '',
            orderId: record.order_id || '',
            withdrawalChannel: record.pay_channel || '',
            withdrawalAmount: record.money || 0,
            withdrawalCoins: record.coin || 0,
            status: this.getStatusText(record.status),
            noRefund: '',
            originalStatus: record.status // 保存原始状态用于后续操作
          }))
          
          // 处理总数
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else if (response.total_page) {
            this.total = response.total_page * this.pageSize
          } else if (response.total) {
            this.total = response.total
          } else {
            this.total = records.length
          }
          
          console.log('设置withdrawalRecords长度:', this.withdrawalRecords.length)
          console.log('当前withdrawalRecords:', this.withdrawalRecords)
          console.log('设置total:', this.total)
          
          // 保存原始数据副本用于筛选
          this.originalRecords = [...this.withdrawalRecords]
          
          // 强制视图更新
          this.$nextTick(() => {
            this.$forceUpdate()
          })
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取提现记录数据失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false
      }
    },
    handleFilter() {
      this.currentPage = 1 // 搜索时重置到第一页
      this.fetchData()
    },
    resetFilter() {
      this.filterForm.channel = null
      this.filterForm = {
        dateRange: [],
        uid: '',
        channel: null,
        pay_channel: '',
        third_order_id: '',
        order_id: '',
        money: '',
        coin: '',
        status: ''
      }
      this.currentPage = 1
      this.fetchData()
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          uid: this.filterForm.uid ? parseInt(this.filterForm.uid) : 0,
          channel: this.formatChannelParam(this.filterForm.channel),
          pay_channel: this.filterForm.pay_channel || '',
          third_order_id: this.filterForm.third_order_id || '',
          order_id: this.filterForm.order_id || '',
          begin_time: this.filterForm.dateRange && this.filterForm.dateRange[0] ? this.filterForm.dateRange[0] : '',
          end_time: this.filterForm.dateRange && this.filterForm.dateRange[1] ? this.filterForm.dateRange[1] : '',
          money: this.filterForm.money ? parseInt(this.filterForm.money) : 0,
          coin: this.filterForm.coin ? parseInt(this.filterForm.coin) : 0,
          status: this.filterForm.status || 0,
          page: 1,
          page_size: 10000
        }
        
        const response = await cashoutRecord(params)
        const allData = response.data.records || []
        
        const columns = [
          { prop: 'create_time', label: '提现时间' },
          { prop: 'uid', label: 'UUID' },
          { prop: 'third_order_id', label: '提现UUID' },
          { prop: 'channel', label: '用户渠道' },
          { prop: 'order_id', label: '订单号' },
          { prop: 'money', label: '提现金额' },
          { prop: 'coin', label: '提现金币' },
          { prop: 'status', label: '提现状态', formatter: (row) => this.getStatusText(row.status) }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `提现记录_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    }
  },
  mounted() {
    this.fetchData()
  }
}
</script>

<style scoped>
.withdrawal-records {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.filter-form {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.red-label ::v-deep .el-form-item__label {
  color: #f56c6c !important;
}

::v-deep .red-column .cell {
  color: #f56c6c !important;
}
</style> 